package com.xiaoyu.lanling.feature.report

import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.net.Uri
import androidx.fragment.app.FragmentActivity
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.ListUtil
import com.xiaoyu.base.utils.RxUtils
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.feedback.*
import com.xiaoyu.lanling.event.media.mediaselector.MediaSelectorResultEvent
import com.xiaoyu.lanling.event.report.ReportPreviewListEvent
import com.xiaoyu.lanling.event.report.ReportPublishAddMediaEvent
import com.xiaoyu.lanling.event.report.ReportPublishPreviewPictureClickEvent
import com.xiaoyu.lanling.feature.report.data.ReportData
import com.xiaoyu.lanling.feature.report.datamodels.ReportMediaItemBase
import com.xiaoyu.lanling.media.selector.MediaSelector
import com.xiaoyu.lanling.media.selector.MediaSelectorFromType
import com.xiaoyu.lanling.media.selector.MediaSelectorType.IMAGE
import com.xiaoyu.lanling.router.Router
import com.xiaoyu.lanling.util.ImageFileCompressUtils
import com.xiaoyu.lanling.view.listener.BaseTextWatcher
import kotlinx.android.synthetic.main.activity_report.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

class ReportController(private val mActivity: FragmentActivity) {

    private var mProgressDialog: ProgressDialog? = null

    private var mAdapter: CubeRecyclerViewSimpleAdapter<ReportMediaItemBase>? = null
    private var editTextWatcher = EditTextWatcher()

    private val requestTag = Any()
    private var mReportData: ReportData? = null

    init {
        initView()
        initAdapter()
        initBind()
        initEvent()
        initData()
    }

    fun onDestroy() {
        mActivity.reportEdit.removeTextChangedListener(editTextWatcher)
    }

    private fun initBind() {
        mActivity.submitButton.setOnClickDebounceListener {
            val content: String = mActivity.reportEdit.text.trim().toString()
            if (mProgressDialog?.isShowing == true || content.isEmpty()) {
                return@setOnClickDebounceListener
            }

            if (mReportData?.report(content) == true) {
                mProgressDialog?.show()
            }
        }
        mActivity.reportEdit.addTextChangedListener(editTextWatcher)
    }

    private fun initView() {
        mActivity.title = mActivity.getString(R.string.report_title)
        mActivity.textCountDesc.text = mActivity.getString(R.string.report_text_count_desc, 0.toString())

        mProgressDialog = ProgressDialog(mActivity)
        mProgressDialog?.setMessage(AppContext.getString(R.string.common_loading_please_wait))
        mProgressDialog?.setCancelable(false)
    }

    private fun initAdapter() {
        mAdapter = CubeRecyclerViewSimpleAdapter()
        ReportViewHolderManager.bindViewHolderForPublish(mAdapter)
        mActivity.reportImageRecyclerview?.adapter = mAdapter
    }

    private fun initData() {
        val type: String? = mActivity.intent.getStringExtra(Constant.PARAM_TYPE)
        val objectId: String? = mActivity.intent.getStringExtra(Constant.IntentKey.KEY_REPORT_OBJECT_ID)
        val reason: String? = mActivity.intent.getStringExtra(Constant.IntentKey.KEY_REPORT_REASON)

        mReportData = ReportData(requestTag, type, reason, objectId)
        mReportData?.loadData()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(mActivity, object : SimpleEventHandler() {

            @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
            fun onEvent(event: ReportPreviewListEvent) {
                mAdapter?.list = event.list
                mAdapter?.notifyDataSetChanged()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: ReportPublishAddMediaEvent) {
                openGallery()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: FeedbackEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                mProgressDialog?.dismiss()

                if (event.isFailed) {
                    return
                }
                GlobalUI.getInstance().showToast(mActivity.getString(R.string.feedback_finished))
                mActivity.finish()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: ReportPublishPreviewPictureClickEvent) {
                if (event.item.position < 0) {
                    return
                }
                val pictureList: ArrayList<String> = ArrayList(mReportData?.pictureBrowseList
                        ?: emptyList())
                if (pictureList.isNotEmpty()) {
                    Router.instance.gotoPhotoActivity(mActivity, event.item.path, pictureList)
                }
            }

            @Subscribe
            fun onEvent(event: FeedbackDeletePictureEvent) {
                mReportData?.removePicture(Uri.parse(event.url))
            }

            @SuppressLint("CheckResult")
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: MediaSelectorResultEvent) {
                if (event.fromType != MediaSelectorFromType.FEEDBACK) {
                    return
                }

                if (event.mediaPathList.isEmpty()) {
                    return
                }

                if (event.type == IMAGE) {
                    ImageFileCompressUtils.compressBatchAsFile(event.imagePathList)
                            .compose(RxUtils.ioToMainSingleScheduler())
                            .filter { paths -> paths.isNotEmpty() }
                            .subscribe({ paths ->
                                val pictureUris = ListUtil.convertToList(paths.asList()) { it -> Uri.fromFile(File(it)) }
                                mReportData?.addPicture(pictureUris)
                            }, { it.printStackTrace() })
                }
            }
        })
    }

    private fun openGallery() {
        if (mReportData == null) {
            return
        }

        MediaSelector.instance.selectorForImage(mReportData?.imageAddAbleCount
                ?: 1, true, MediaSelectorFromType.FEEDBACK)
    }

    private inner class EditTextWatcher : BaseTextWatcher() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            s?.let {
                mActivity.textCountDesc.text = mActivity.getString(R.string.feedback_text_count_desc, it.length.toString())
                mActivity.submitButton.isEnabled = it.isNotEmpty()
            }
        }
    }
}
